<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use app\common\model\member\Wallet;
use app\common\model\member\WalletRecharge;
use buwang\base\MemberBaseController;
use buwang\facade\WechatPay;
use buwang\util\alipay\AliPay;
use dh2y\qrcode\QRcode;
use think\facade\Cache;
use think\facade\Request;
use think\facade\View;

/**
 * @ControllerAnnotation(title="租户充值")
 */
class Recharge extends MemberBaseController
{
    public function initialize()
    {
        parent::initialize();
        $this->layout && $this->app->view->engine()->layout($this->layout);
    }

    public function index()
    {
        $money = Wallet::where('member_id', $this->uid)->value('money') ?: 0;
        if ($this->request->isAjax()) {
            return $this->success('success', $money);
        }
        View::assign('money', $money);
        return view();
    }

    public function pay()
    {
        if ($this->request->isPost()) {
            $pay_type = $this->request->post('pay_type/s');
            $money = $this->request->post('money/f');

            if (!in_array($pay_type, ['wechat', 'alipay'])) return $this->error('支付方式有误');
            if($money < 10) return $this->error('充值金额最低为10元');

            $member = $this->user;
            $member_id = $member['id'];
            if(!$member_id){
                return $this->error('获取租户信息失败');
            }

            $order_sn = get_uuid();
            $type = $pay_type == 'wechat' ? 0 : 1;

            $res = WalletRecharge::create(compact('member_id', 'order_sn', 'money', 'type'));
            if (!$res) return $this->error('充值记录创建失败');

            //alipay-wechat
            if ($pay_type == 'wechat') {
                $order = [
                    'trade_type' => 'NATIVE',
                    'body' => '充值',
                    //'time_expire'=>date("c", time()+301),
                    'out_trade_no' => $order_sn,
                    'total_fee' => $money * 100,//分
                    'notify_url' => (string)url('/manage/recharge/notify', [], false, true),
                ];
                $wechat = WechatPay::doPay();
                //判断错误返回
                if (is_array($wechat)) {
                    return $this->error($wechat['msg']);
                }
                $result = $wechat->order->unify($order);
                //订单创建失败
                if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') return $this->error('微信订单创建失败'.$result['return_msg']);

                $code = new QRcode();
                // 生成唯一文件名
                $filename = 'qrcode_' . $order_sn . '.png';
                //前端访问路径
                $filepath = config('qrcode.cache_dir') . DIRECTORY_SEPARATOR;
                //存储路径
                $basepath = 'public'. DIRECTORY_SEPARATOR . $filepath;
                if (!file_exists($basepath)){
                    mkdir ($basepath,0775,true);
                }
                //// 获取二维码生成的地址
                $code_url = $code->png($result['code_url'], $basepath.$filename)->getPath();

                //$code_url = $code->png($result['code_url'], config('qrcode.cache_dir'))->getPath(); // 获取二维码生成的地址
                $data = [
                    //'code_url' => Request::instance()->domain().$code_url,
                    'code_url' => Request::instance()->domain().DIRECTORY_SEPARATOR.$filepath.$filename,
                    'code_url_origin' => $result['code_url'],
                    'out_trade_no'  =>  $order_sn,
                    'total_fee' =>  $money,
                    'expire_time'=>time()+301//5分钟
                ];
            } else {
                //支付宝PC支付
                $aliPay = new AliPay();
                $totalAmount = bcadd((string)$money, "0",2);
                $res = $aliPay->paymentFaceToFace('recharge','充值订单',$order_sn,$totalAmount);
                if(!$res){
                    return $this->error('支付宝支付失败');
                }

                $code = new QRcode();
                // 生成唯一文件名
                $filename = 'qrcode_' . $order_sn . '.png';
                //前端访问路径
                $filepath = config('qrcode.cache_dir') . DIRECTORY_SEPARATOR;
                //存储路径
                $basepath = 'public'. DIRECTORY_SEPARATOR . $filepath;
                if (!file_exists($basepath)){
                    mkdir ($basepath,0775,true);
                }
                // 获取二维码生成的地址
                $code_url = $code->png($res->qrCode, $basepath.$filename)->getPath();

                $data = [
                    'code_url' => Request::instance()->domain().DIRECTORY_SEPARATOR.$filepath.$filename,
                    'code_url_origin' => $res->qrCode,
                    'out_trade_no'  =>  $order_sn,
                    'total_fee' =>  $money,
                    'expire_time'=>time()+301//5分钟
                ];
            }

            //延时队列
            //->do('sendSubscribeMessage')
            $isPushed=\buwang\base\Queue::instance()->secs(301)->job(\buwang\jobs\SystemCommonJob::class)->data($order_sn)->push();
            if ($isPushed == false) {
                throw new \Exception("push a new queue Job Failed!");
            }
            return $this->success('提交成功', $data);
        }
        return true;
    }

    /**
     *获取支付宝PC支付页面
     */
    public function page()
    {
        $member = $this->user;
        $member_id = $member['id'];
        if(!$member_id){
            return $this->error('获取租户信息失败');
        }
        $page = Cache::store('redis')->get("zhifu_message_{$member_id}");
        if(!$page){
            return $this->error('订单已过期，请重新下单'.$member_id);
        }

        return response($page)->contentType('text/html');
    }

//    public function pay()
//    {
//        if ($this->request->isPost()) {
//            $pay_type = $this->request->post('pay_type/s');
//            $money = $this->request->post('money/f');
//
//            if (!in_array($pay_type, ['wechat', 'alipay'])) return $this->error('支付方式有误');
//            if($money < 10) return $this->error('充值金额最低为10元');
//
//            $member = $this->user;
//
//            $member_id = $member['id'];
//            $order_sn = get_uuid();
//            $type = $pay_type == 'wechat' ? 0 : 1;
//
//            $res = WalletRecharge::create(compact('member_id', 'order_sn', 'money', 'type'));
//            if (!$res) return $this->error('充值记录创建失败');
//
//            if ($pay_type == 'wechat') {
//                $order = [
//                    'trade_type' => 'NATIVE',
//                    'body' => '充值',
//                    //'time_expire'=>date("c", time()+301),
//                    'out_trade_no' => $order_sn,
//                    'total_fee' => $money * 100,//分
//                    'notify_url' => (string)url('/manage/recharge/notify', [], false, true),
//                ];
//                $wechat = WechatPay::doPay();
//                //判断错误返回
//                if (is_array($wechat)) {
//                    return $this->error($wechat['msg']);
//                }
//                $result = $wechat->order->unify($order);
//                //订单创建失败
//                if ($result['return_code'] != 'SUCCESS' || $result['result_code'] != 'SUCCESS') return $this->error('微信订单创建失败'.$result['return_msg']);
//
//                $code = new QRcode();
//                $code_url = $code->png($result['code_url'], config('qrcode.cache_dir'))->getPath(); // 获取二维码生成的地址
//            } else return $this->error('不支持的支付方式');
//            $data = [
//                'code_url' => Request::instance()->domain().$code_url,
//                'code_url_origin' => $result['code_url'],
//                'out_trade_no'  =>  $order_sn,
//                'total_fee' =>  $money,
//                'expire_time'=>time()+301//5分钟
//            ];
//            //延时队列
//            //->do('sendSubscribeMessage')
//            $isPushed=\buwang\base\Queue::instance()->secs(301)->job(\buwang\jobs\SystemCommonJob::class)->data($order_sn)->push();
//            if ($isPushed == false) {
//                throw new \Exception("push a new queue Job Failed!");
//            }
//            return $this->success('提交成功', $data);
//        }
//
//    }

    /**
     * 定时检测订单支付状态
     * @return \think\Response
     */
    public function checkOrderStatus()
    {
        if ($this->request->isGet()) {
            $order_sn = $this->request->get('order_sn/s');
            $order =WalletRecharge::where('order_sn',$order_sn)->find();
            if(!$order) return $this->error('订单不存在！');
            if($order['state'] ==1 && $order['transaction_id']) {
                return $this->success('支付成功', ['status'=>1]);
            }else if($order['state'] ==2){
                return $this->error('订单超时，请重新下单', ['status'=>2]);
            }
        }else{
            return $this->error('请求方式错误');
        }
        return $this->success('查询成功', ['status'=>0]);
    }
}